package com.ppch.wuwamanus.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Package:WuWaManus
 * ClassName:CosClientConfig
 *
 * @Author 泡泡茶壶
 * @Create 2025/8/10 17:36
 * @Version 1.0
 * Description:
 */
@Configuration  // 增加此注解，标识为配置类
@ConfigurationProperties(prefix = "cos.client")  // 绑定cos.client前缀的配置
@EnableConfigurationProperties
@Data
public class CosClientConfig {

    /**
     * 域名
     */
    private String host;

    /**
     * secretId
     */
    private String secretId;

    /**
     * 密钥（注意不要泄露）
     */
    private String secretKey;

    /**
     * 区域
     */
    private String region;

    /**
     * 桶名
     */
    private String bucket;

    @Bean
    public COSClient cosClient() {
        // 验证配置
        if (StringUtils.isBlank(secretId) || StringUtils.isBlank(secretKey) ||
                StringUtils.isBlank(host) || StringUtils.isBlank(bucket) || StringUtils.isBlank(region)) {
            throw new IllegalStateException("SecretId:" + secretId + ", SecretKey:" + secretKey +
                    ", host:" + host + ", bucket:" + bucket + ", region:" + region);
        }
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
        // 2 设置 bucket 的地域
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }
}
